<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/12 18:04
 * @version
 */
namespace Modules\Api\Controllers;

use App\Models\Configure;
use App\Models\Coupon;
use App\Models\MobileRecharge;
use App\Models\MobileRechargeOrder;
use App\Models\MobileRechargeTask;
use App\MobileRecharge as MobileRechargeService;
use App\Models\Pay;
use App\Models\User;
use App\Models\UserCoupon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Token\Facades\Token;


class MobileRechargeController extends Controller
{
    public function demo(Request $request)
    {
        //$status = MobileRechargeService::onlineOrder('15958758319',30,time());
        //return success($status);
    }

    public function index()
    {
        //$uid  = Token::data('id');
        //$user = User::find($uid);

        $data = [
            'items'     => [],
        ];

        $data['items'] = MobileRecharge::orderBy('discount', 'desc')->get()->toArray();

        $data['discount'] = (string)Configure::rechargeDiscount();

        $data['amounts'] = [
            '30',
            '50',
            '100',
            '200',
            '400',
            '500'
        ];

        return success($data);
    }

    public function store(Request $request)
    {
        try {
            DB::beginTransaction();
            $user = User::find(Token::data('id'));

            if (!$user) {
                return fail(403, '用户不存在');
            }

            $mobile   = $request->input('mobile');
            $amount      = $request->input('amount');
            $rechargeId  = $request->input('recharge_id');
            $useCouponId = $request->input('use_coupon_id');
            $openId      = $request->input('open_id');

            $paymentMethod = $request->input('payment_method', 'weixin');

            if (!$user['open_id'] && !$openId && $paymentMethod == 'weixin') {
                return fail(400, 'open_id不能为空');
            }

            if ($openId) {
                User::where('id', $user['id'])->update(['open_id' => $openId]);
            }


            if (!$amount) {
                return fail(400, '参数错误');
            }

            $amount = formatPrice($amount);

            //是否使用优惠券
            if ($useCouponId) {
                $useCoupon = UserCoupon::where('status', UserCoupon::STATUS_NEW)
                    ->where('user_coupon.id', $useCouponId)
                    ->where('user_id', $user->id)
                    ->first();
                if (!$useCoupon OR $useCoupon->isExpired()) {
                    return fail(400, '优惠券无效，请重新选择');
                    Log::error();
                }

                $months = 1;

                if($rechargeId){
                    $recharge = MobileRecharge::find($rechargeId);
                    if (!$recharge) {
                        return fail(400, '套餐不存在');
                    }
                    $months = $recharge->months;
                }

                //验证优惠券的合法性
                $couponInfo = Coupon::query()->find($useCoupon->coupon_id);
                if(!$couponInfo) return fail(1016,'无效的优惠券');
                //验证消费金额
                $totalAmount = $amount * $months;
                if($couponInfo->min_amount > 0 && $totalAmount < $couponInfo->min_amount){
                    Log::error('coupon error:' . $useCoupon->user_id . '-' . $useCoupon->id);
                    return fail(1016,'优惠券无效,充值金额不满足使用条件');
                }

                //冻结优惠券
                $useCoupon->status = 4;
                $useCoupon->used_at = Carbon::now();
                $useCoupon->save();

            } else {
                $useCoupon = null;
            }

            // 套餐充值
            if ($rechargeId) {

                // 是否是首充
                $isFirst = true;
                if (MobileRechargeOrder::where('user_id', $user->id)->where('status', '>', 0)->count()) {
                    $isFirst = false;
                }

                $recharge = MobileRecharge::find($rechargeId);
                if (!$recharge) {
                    return fail(400, '套餐不存在');
                }

                //套餐支付金额
                $payAmount = formatPrice(($amount * $recharge->months) * $recharge->discount);
                // 使用优惠券
                if ($useCoupon) {
                    // 代金券
                    if ($useCoupon->type == UserCoupon::TYPE_MONEY) {
                        $payAmount = $payAmount - $useCoupon->amount;
                        //$payAmount = $payAmount < 0 ? 0 : $payAmount;
                        if($payAmount <= 0){
                            return fail(400,'优惠券无效');
                        }
                    }
                    // 特权券，可以使用首充限制的套餐
                    if ($useCoupon->type == UserCoupon::TYPE_RECHARGE && $useCoupon->recharge_id == $recharge->id) {
                        $isFirst = true;
                    }
                }

                // 是不是仅限首充
                if ($recharge->only_first) {
                    if (!$isFirst) {
                        return fail(400, '只有首次充值才能选择此套餐');
                    }
                }

                if (!$useCouponId) {
                    $useCouponId = 0;
                }


                $attrs = [
                    'type' => 1,
                    'user_id'=>$user->id,
                    'mobile'=>$mobile,
                    'recharge_id'=>$rechargeId,
                    'recharge_amount'=>$amount,
                    'pay_amount'=>$payAmount,
                    'months'=>$recharge->months,
                    'coupon_id'=>$useCouponId,
                    'discount'=>$recharge->discount,
                    'status'=>0
                ];

                $order = new MobileRechargeOrder($attrs);
            } else {
                // 直接充值

                $payAmount = formatPrice($amount * Configure::rechargeDiscount());

                // 使用优惠券
                if ($useCoupon) {
                    if ($useCoupon->only_recharge) {
                        return fail(400, '优惠券仅限充值套餐时使用');
                    }
                    if ($useCoupon->type == UserCoupon::TYPE_MONEY) {
                        //$payAmount = $payAmount - $useCoupon->amount;
                        //$payAmount = $payAmount < 0 ? 0 : $payAmount;
                    }
                }

                if (!$useCouponId) {
                    $useCouponId = 0;
                    // Log::error('11111');
                }

                if (!$rechargeId) {
                    $rechargeId = 0;
                    // Log::error('22222');
                }


                $attrs = [
                    'type' => 2,
                    'user_id'=>$user->id,
                    'mobile'=>$mobile,
                    'recharge_id'=>$rechargeId,
                    'recharge_amount'=>$amount,
                    'pay_amount'=>$payAmount,
                    'coupon_id'=>$useCouponId,
                    'discount'=>Configure::rechargeDiscount(),
                    'status'=>0
                ];

                $order = new MobileRechargeOrder($attrs);

            }

            // 创建支付单
            $pay = new Pay([
                'payment_method'=>$paymentMethod,
                'user_id'=>$user->id,
                'pay_sn'=>Pay::makeHuaFeiPaySN(),
                'amount'=>$order['pay_amount']
            ]);

            $pay->save();
            $order->pay_id = $pay->id;
            $order->save();
            $response = [
                'order_id'       => $order->id,
                'payment_method' => $paymentMethod,
                'pay_info'       => null,
            ];
            $response['pay_info']   = '';
            $response['weixin_app'] = null;
            if ($paymentMethod == 'alipay') {
                $response['pay_info'] = Pay::alipay_number($pay);
            }
            if ($paymentMethod == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp_number($pay);
            }
            if ($paymentMethod == 'weixin') {
                $response['weixin'] = Pay::weixin_number($pay, $openId);
            }

            DB::commit();

            return success($response);
        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            return fail(500, '系统错误');
        }
    }

    public function pay($id, Request $request)
    {
        try {
            $order         = MobileRechargeOrder::find($id);
            $paymentMethod = $request->input('payment_method');
            $user = User::find(Token::data('id'));

            $pay                 = $order->pay;
            $pay->payment_method = $paymentMethod;
            $pay->save();

            $response = [
                'order_id'       => $order->id,
                'payment_method' => $paymentMethod,
                'pay_info'       => null,
            ];
            if ($pay->pay_sn) {
                $pay->pay_sn = Pay::makeHuaFeiPaySN();
            }
            $response['pay_info']   = '';
            $response['weixin_app'] = null;
            if ($paymentMethod == 'alipay') {
                $response['pay_info'] = Pay::alipay_number($pay);
            }
            if ($paymentMethod == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp_number($pay);
            }
            if ($paymentMethod == 'weixin') {
                $response['weixin'] = Pay::weixin_number($pay, $user['open_id']);
            }
            return success($response);
        } catch (\Exception $e) {
            Log::error($e);
            return fail(500, '系统错误');
        }
    }

    public function order(Request $request)
    {
        $type   = $request->input('type');
        $status = $request->input('status', false) ?: false;
        $orderId = $request->input('orderId', false) ?: false;

        $user   = User::find(Token::data('id'));
        
        $limit  = $request->input('limit', 20);
        $offset = $request->input('offset', 0);

        if ($orderId) {
            DB::table('mobile_recharge_order')->where('id', $orderId)->update(['status' => -1]);
        }
        
        if ($type) {
            $query = $query->where('type', $type);
        }

        $query = MobileRechargeOrder::query();
        if ($status == 0) {
            $query = $query->where('status', MobileRechargeOrder::STATUS_INIT)    //待支付 0
            ->where('user_id', $user->id);
            $data['total'] = $query->count();
            for ($i=0; $i < $query->count(); $i++) {
               $data['items'] = $query->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $data['items'][$key]['nickname'] = $value['recharge_amount'].'元话费直充';
                        $data['items'][$key]['months'] = 1;
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月话费套餐';
                    } 
                }
            }
        }
        if ($status == 1) {
            $query_two = MobileRechargeOrder::query();
            $query_two = $query_two->where('status', MobileRechargeOrder::STATUS_PAID)      //进行中  1
            ->where('user_id', $user->id);
            $data['total'] = $query_two->count();
            for ($i=0; $i < $query_two->count(); $i++) {
               $data['items'] = $query_two->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $data['items'][$key]['nickname'] = $value['recharge_amount'].'元话费直充';
                        $data['items'][$key]['months'] = 1;
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月话费套餐';
                    } 
                }
            }   
        }
        if ($status == 3) {
            $query_three = MobileRechargeOrder::query();
            $query_three = $query_three->where('status', MobileRechargeOrder::STATUS_DONE)   //已完成   3
            ->where('user_id', $user->id);
            $data['total'] = $query_three->count();
            for ($i=0; $i < $query_three->count(); $i++) {
               $data['items'] = $query_three->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $data['items'][$key]['nickname'] = $value['recharge_amount'].'元话费直充';
                        $data['items'][$key]['months'] = 1;
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月话费套餐';
                    } 
                }
            }   
        }
        if ($status == 5) {
            $query_four = MobileRechargeOrder::query();
            $query_four = $query_four->where('user_id', $user->id);   //全部    5
            $data['total'] = $query_four->count();
            for ($i=0; $i < $query_four->count(); $i++) {
               $data['items'] = $query_four->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $data['items'][$key]['nickname'] = $value['recharge_amount'].'元话费直充';
                        $data['items'][$key]['months'] = 1;
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月话费套餐';
                    } 
                }
            }   
        }
        if ($status == -1) {
            $query_five = MobileRechargeOrder::query();
            $query_five = $query_five->where('status', -1)       //已退订   -1
            ->where('user_id', $user->id);
            $data['total'] = $query_five->count();
            for ($i=0; $i < $query_five->count(); $i++) {
               $data['items'] = $query_five->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $data['items'][$key]['nickname'] = $value['recharge_amount'].'元话费直充';
                        $data['items'][$key]['months'] = 1;
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月话费套餐';
                    } 
                }
            }   
        }
        $query->when($status, function ($q) use ($status) {
            $q->where('status', $status);
        });

         return success($data);
    }

    public function order_detail(Request $request)
    {
        $type   = $request->input('type');
        $orderid = $request->input('order_id');
        $query_two = MobileRechargeOrder::where('id',$orderid)->get();
        //取订单任务表的详细数据
        if (!empty($orderid) && $query_two[0]['status'] == 1 or $query_two[0]['status'] == 3) {
            $query_one = MobileRechargeTask::where('recharge_order_id',$orderid)->orderBy('pay_at', 'asc')->get();//根据订单id 查询充值详情列表
            $query_two = MobileRechargeOrder::where('id',$orderid)->get();
            for ($i=0; $i < $query_one->count(); $i++) { 
                $data['items'] = $query_one;
                $a = 1;
                foreach ($query_one as $key => $value) {
                    $data['status'] = $query_two[0]['status'];
                    $data['card_type'] = $value->card_type;
                    $data['mobile'] = $value->card_mobile;
                    $data['recharge_order_detail_id'] = $value->recharge_order_detail_id;
                    $data['recharge_amount'] = $query_two[0]['recharge_amount'];
                    $data['coupon_id'] = $query_two[0]['coupon_id'];
                    $data['pay_amount'] = $query_two[0]['pay_amount'];
                    $data['order_id'] = $query_two[0]['id'];

                    $c = $query_two[0]['created_at'];
                    $year = date('Y-m-d',strtotime($c));
                    $data['created_at'] = $year;

                    $data['items'][$key]['benqi'] = intval($query_two[0]['recharge_amount']);
                    $data['items'][$key]['months'] = $query_two[0]['months'];
                    $data['items'][$key]['qishu'] = $a++;

                    $year = date('Y-m-d',strtotime($value->pay_at));
                    $data['items'][$key]['pay_at'] = $year;

                    $years = date('Y-m-d',strtotime($value->created_at));
                    $data['items'][$key]['created_two_at'] = $years;

                    if ($query_two[0]['coupon_id']) {
                        $sql = UserCoupon::where('id',$query_two[0]['coupon_id'])->get();
                        if ($sql) {
                            $data['coupon_id'] = $sql[0]['title'];
                        }
                    }
                }
            }
        }

        
        
        if (!empty($orderid) && $query_two[0]['status'] == 0 or $query_two[0]['status'] == -1) {
                    $user = DB::table('user')->where('id', $query_two[0]['user_id'])->first();
                    $arr = array();
                    $data['items'] = $arr;
                    $data['mobile'] = $user->mobile;
                    $data['status'] = $query_two[0]['status'];
                    $data['recharge_amount'] = $query_two[0]['recharge_amount'];
                    $data['pay_amount'] = $query_two[0]['pay_amount'];
                    $data['order_id'] = $query_two[0]['id'];

                    $c = $query_two[0]['created_at'];
                    $year = date('Y-m-d',strtotime($c));
                    $data['created_at'] = $year;

                    $data['recharge_type'] = $query_two[0]['type'];
                    if ($query_two[0]['coupon_id']) {
                        $sql = UserCoupon::where('id',$query_two[0]['coupon_id'])->get();
                        if ($sql) {
                            $data['coupon_id'] = $sql[0]['title'];
                        }
                    }else{
                        $data['coupon_id'] = '未使用优惠券';
                    }
        }
        return success($data);
    }
}